<?php
    @session_start();
    require_once 'shared-functions.php';
    require_once 'session.php';
    require_once 'masterpage.php';

    if(!IsValidSession())
    {
        header('Location: login.php?page=index');
        exit();
    }
    else
    {
        RefreshSession();
    }

    $user = GetCurrentUserAccessLevel();
    //Check user access
    if($user != $DIRECTOR && $user != $ADMIN && $user != $PRINCIPLE)
    {
        header('Location: login.php?page=manage-semesters&error=To access to the manage semesters page, please log in as a director or admin&logout=1');
        exit();
    }

    masterpage("Add classes to semester");

    $AddSemester = "";
    if(isset($_POST['AddSemester']))
        $AddSemester = $_POST["AddSemester"];
    $classes = "";	
    $teachers = "";

    if (isset($_POST["semesterID"]))
    {    
	    $semesterID = $_POST["semesterID"];
	try
	{
		$link = connect_db();
	
		$currentSemesterQuery = "SELECT `semesterID`,`StartDate`,`EndDate`,`Description` FROM `Semester` where semesterID = '$semesterID'";
		$classQuery = "SELECT courseID, name FROM Course;";
		$teacherQuery = "SELECT UserID, FirstName, MiddleName, LastName FROM User where PrivilegeLevel = '2';";


		if ($AddSemester == 1)
		{
			$newClass = $_POST["newClass"];
			$newTeacher = $_POST["newTeacher"];
			$daysTaught = $_POST["daysTaught"];

			if (strlen($daysTaught) > 0)
			{
				$insertClassQuery = "insert into CourseInstance (CourseID, instructorID, DaysTaught, semesterID) values";
				$insertClassQuery .= "('$newClass', '$newTeacher', '$daysTaught', '$semesterID')";

				if (!mysql_query($insertClassQuery, $link))
				{
					die('Error: ' . mysql_error());
				}	
			}		
		}
		

		$currentSemesterResult = mysql_query($currentSemesterQuery, $link);
		$classQueryResult = mysql_query($classQuery, $link);
		$teacherQueryResult = mysql_query($teacherQuery, $link);

		$rowID = 0;

		// Load the Semester from the ID that was passed in
		if($currentSemesterResult===false)
		{
			$_SESSION['error']="Could not get semester details. - edit-semesters.php";
			return false;
		}
		else
		{

			while($semesterRow = mysql_fetch_array($currentSemesterResult, MYSQL_ASSOC))
			{	
				$id = $semesterRow["semesterID"];
				$startDate = $semesterRow["StartDate"];
				$endDate = $semesterRow["EndDate"];
				$desc = $semesterRow["Description"];
			}
		}

		// Load all the classes from the database

		

		if($classQueryResult===false)
		{
			$_SESSION['error']="Could not get class details. - edit-semesters.php";
			return false;
		}
		else
		{			
			$firstRow = true;

			while($currentClassesRow = mysql_fetch_array($classQueryResult, MYSQL_ASSOC))
			{	
				if ($firstRow)
				{
					$selectedOption = "selected='selected'";
					$firstRow = false;
				}
				else
				{
					$selectedOption = "";
				}

				$userID = $currentClassesRow["courseID"];
				$name = $currentClassesRow["name"];
				$classes .= "<option value='$userID' $selectedOption>$name</option>";
			}
		}

		// Get list of all teachers from User table
		if($teacherQueryResult===false)
		{
			$_SESSION['error']="Could not get teacher details. - edit-semesters.php";
			return false;
		}
		else
		{
			$firstRow = true;

			while($teachersRow = mysql_fetch_array($teacherQueryResult, MYSQL_ASSOC))
			{	
				if ($firstRow)
				{
					$selectedOption = "selected='selected'";
					$firstRow = false;
				}
				else
				{
					$selectedOption = "";
				}

				$teacherID = $teachersRow["UserID"];
				$firstName = $teachersRow["FirstName"];
				$middleName = $teachersRow["MiddleName"];
				$lastName = $teachersRow["LastName"];
				$teachers .= "<option value='$teacherID' $selectedOption>$firstName $middleName $lastName</option>";
			}
		}
	}
	catch (Exception $exception)
	{
		$_SESSION['error']=$exception->getMessage();
		return false;
	}
		
?>
	
   	<table class="DataList" style="width:550px;">
		<thead>
			<tr>
				<th class="header" colspan="2">Add Classes to Semester</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td class="rows" colspan="2" style="text-align:center;"><?php echo$desc;?></td>
			</tr>
			<tr>
				<td  class="rows" colspan="2" style="text-align:center;"><span style="color:gray;">Start:</span> <?php echo DisplayDate($startDate);?>, 
					<span style="color:gray;">End:</span> <?php echo DisplayDate($endDate);?></td>
			</tr>
		</tbody>
	    </table>
    	<p></p>
    	<form action="add-classes-to-semester.php" name="AddClassesToSemester" method="post">
	    <input type="hidden" value="<?php echo $semesterID;?>" name="semesterID">
	    <input type="hidden" value="1" name="AddSemester">
	    <table id="addClasses" class="DataList" style="width:550px;">
		<thead>
			<tr>
				<th class="header" colspan="2">Add a Class</th>
			</tr>
		</thead>
		<tbody>
			<tr> <td>&nbsp;</td><td> <span style="color:red;">&nbsp;All Fields are required.</span></td></tr>
			<tr>
				<td class="rows">Select a Class:</td>
				<td class="rows">
				    <select name="newClass" id="newClass" size="4" style="width:250px">
					<?php echo $classes; ?>
				    </select>
				    <span style="color:red;">&nbsp;*</span>
				</td>
			</tr>
			<tr>
				<td class="rows">Select a Teacher:</td>
				<td class="rows">
				    <select name="newTeacher" id="newTeacher" size="4" style="width:250px">
					<?php echo $teachers; ?>
				    </select>
				    <span style="color:red;">&nbsp;*</span>
				</td>
			</tr>	
			<tr>
				<td class="rows">Days Taught:</td>
				<td class="rows">
				    <input name="daysTaught" id="newDaysTaught" style="width:245px;">
				    <span style="color:red;">&nbsp;*</span>
				</td>
			</tr>				
			<tr>
				<td colspan="2" class="rows" style="text-align:center;"><input type="submit" value="Add Class"></td>
			</tr>
		</tbody>
	    </table>
	</form>
	
	<table id="removeClasses" class="DataList" style="width:550px;">
		<thead>
			<tr>
				<th class="header" colspan="4">Classes</th>
			</tr>
			<tr>
				<th class="header">&nbsp;</th>
				<th class="header">Course</th>
				<th class="header">Teacher</th>
				<th class="header">Schedule</th>
			</tr>
		</thead>
		<tbody>
		<?php
		// This section retrieves the Class data to fill in the table below.

		try
		{
			$link = connect_db();
			
			$query = "select CourseInstance.InstanceID, Course.Name, User.FirstName, User.LastName, CourseInstance.DaysTaught from CourseInstance";
			$query .= " left join User on CourseInstance.InstructorID = User.UserID";
			$query .= " left join Course on CourseInstance.CourseID = Course.CourseID where semesterID = '$semesterID'";

			$result = mysql_query($query, $link);

			$rowID = 0;

			if($result===false)
			{
				$_SESSION['error']="Could not get class details. - add-classes-to-semester.php";
				echo "<tr><td colspan='2' style='text-align:center;'>No classes found.</td></tr>";
			}
			else
			{
				while($classRow = mysql_fetch_array($result, MYSQL_ASSOC))
				{	
					$id = $classRow["InstanceID"];
					$courseName = $classRow["Name"];
					$instructorName = $classRow["FirstName"] ." ".$classRow["LastName"];
					$daysTaught = $classRow["DaysTaught"];


					if ($rowID == 0)
					{
						$rowClass = "rows";
						$rowID++;
					}
					else
					{
						$rowClass = "altrows";
						$rowID--;
					}
					echo "<form action='edit-course-instance.php' method='POST'>";
						echo "<input type='hidden' name='courseInstanceID' value='$id'/>";
						echo "<input type='hidden' name='semesterID' value='$semesterID'/>";
						echo "<tr>";
							echo "<td class='$rowClass'> <input type='submit' value='Edit'></td>";
							echo "<td class='$rowClass'>$courseName</td>";
							echo "<td class='$rowClass'>$instructorName</td>";
							echo "<td class='$rowClass'>$daysTaught</td>";
						echo "</tr>";
					echo "</form>";
				}
			}
		}
		catch (Exception $exception)
		{
			$_SESSION['error']=$exception->getMessage();
			echo"Can't retrieve any details.";
		}
		
	?>
		</tbody>
	</table>

	<script type="text/javascript">
		
	</script>
<?php
	}
	else {
	    echo "You must first visit <a href='manage-semesters.php'>this page</a> to choose a semester.";
	}
	endmasterpage();
?>
